package edu.zut.software.identity.controller;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.TimeUtil;
import edu.zut.software.identity.Repository.StuInfoRepository;
import edu.zut.software.identity.Repository.StudentRepository;
import edu.zut.software.identity.Service.StuGradeService;
import edu.zut.software.identity.Service.StudentService;
import edu.zut.software.identity.Service.impl.StudentServiceImpl;
import edu.zut.software.identity.domain.StuCollege;
import edu.zut.software.identity.domain.StuGrade;
import edu.zut.software.identity.domain.StuInfo;
import edu.zut.software.identity.domain.Student;

import edu.zut.software.identity.utils.JsonUtil;
import edu.zut.software.identity.utils.WXAPIUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/student")
public class StudentController {
    private static final Logger logger = LoggerFactory.getLogger(CollegeController.class);

    public StudentServiceImpl studentService;

    @Autowired
    public void setStudentService(StudentServiceImpl studentService) {
        this.studentService = studentService;
    }

    public StuGradeService stuGradeService;

    @Autowired
    public void setStuGradeService(StuGradeService stuGradeService) {
        this.stuGradeService = stuGradeService;
    }

    @Autowired
    public StuInfoRepository stuInfoRepository;

    @RequestMapping("/t1")
    public List<Student> findAllStudent() {
        return studentService.findAll();
    }

    @RequestMapping("/save")
    public void sveStudent() {
        Student student = new Student();
        student.setName("张安");
        student.setId("53464");
        studentService.save(student);
    }


    @PostMapping("/saveStudent")
    public String saveStudent(@RequestBody Student student) {
        System.out.println(student);
        studentService.save(student);
        return "success";
    }

    /**
     * 添加学生手机号
     */
    @GetMapping("/modify/{id}/{iphone}")
    public String save(@PathVariable("id") String id, @PathVariable("iphone") String iphone) {
        Student student = studentService.findById(id);
        Date time = new Date();
        student.setTime(time);
        student.setIphone(iphone);
        studentService.save(student);
        if (student.getIphone() == iphone) {
            return "success";
        } else {
            return "error";
        }
    }

    @DeleteMapping("/deleteStudentById/{id}")
    public void deleteStudentById(@PathVariable("id") String id) {
        studentService.deleteById(id);
    }

    @GetMapping("/findStudentById/{id}")
    public Student findStudentById(@PathVariable("id") String id) {
        return studentService.findById(id);
    }

    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/findById/{id}")
    public String findById(@PathVariable("id") String id) {
        Student student = studentRepository.findById(id).orElse(null);
        if (student != null) {
            return "success";
        } else {
            return "error";
        }

    }


    /**
     * 创建成员
     */
    @RequestMapping("/register")
    public void register() {
        List<Student> students = studentService.findAll();
        for (Student userInfo : students) {
            Map<String, Object> map = new HashMap<String, Object>() {
                {
                    put("userid", userInfo.getId());
                    put("name", userInfo.getName());
                    put("mobile", userInfo.getIphone());
                    put("order", Arrays.asList(10000 - userInfo.getPx()));
                    // put("position", userInfo.getZw());
                    // put("gender", userInfo.getXb());
                    //put("to_invite", false);
                }
            };
            int gradeId = stuGradeService.findById(userInfo.getGradeId()).getWx_id();
            int[] ints = new int[]{gradeId};
            System.out.println(map.get("mobile"));
            if (map.get("mobile") != null) {
                map.put("department", ints);
                logger.info("注册信息:{}", JsonUtil.toJson(map));
                Map<String, Object> jsonMap = WXAPIUtil.createContact(JsonUtil.toJson(map));
                logger.info("返回信息:{}", JsonUtil.toJson(jsonMap));
                if (Integer.parseInt(jsonMap.get("errcode").toString()) == 0) {
                    //  userInfo.setWx_id(Integer.parseInt(jsonMap.get("id").toString()));
                    studentService.save(userInfo);
                }
            }
        }
    }

    @GetMapping("/searchStudent/{page}/{number}")
    //  @ResponseBody
    public Page<Student> searchStudent(@PathVariable Integer page, @PathVariable Integer number) {
        return studentService.findAll(page - 1, number);
    }

    //    @PostMapping("/search/{page}/{number}")
//    //  @ResponseBody
//    public Page<StuInfo> search(@PathVariable Integer page, @PathVariable Integer number, @RequestParam String name) {
//        if(number == null && number.equals(0)){
//            number = 15;
//        }
//        return studentService.findAll(page-1, number, name);
//    }
    @GetMapping("/search/{page}/{number}/{name}")
    //  @ResponseBody
    public Page<StuInfo> search(@PathVariable Integer page, @PathVariable Integer number, @PathVariable String name) {
        if (number == null && number.equals(0)) {
            number = 15;
        }
        Pageable pageable = PageRequest.of(page, number);
        Page<StuInfo> pageInfo = stuInfoRepository.findAll(pageable);
        return pageInfo;
    }

    @PostMapping("/search/{page}/{number}")
    //  @ResponseBody
    public Page<StuInfo> search(@PathVariable Integer page, @PathVariable Integer number, @RequestBody StuInfo stuInfo) {
        if (number == null && number.equals(0)) {
            number = 15;
        }
        return studentService.findAll(page - 1, number, stuInfo);
    }

    //    @GetMapping("/getCount")
//    public String getCount(){
//        Map<Date, Integer>map=new HashMap<>();
//        List<Map<Date, Integer>>mapList=studentService.getCount();
//        String json = JSON.toJSONString(mapList);
//        System.out.println(json);
//        return   json;
//    }
    @GetMapping("/getCount")
    List<Map<Date, Integer>> getCount() {
        Map<Date, Integer> map = new HashMap<>();
        List<Map<Date, Integer>> mapList = studentService.getCount();
        return mapList;
    }

    @GetMapping("export")
    public ResponseEntity<byte[]> export() throws UnsupportedEncodingException {
        String savePath = "";
        HttpHeaders headers = null;
        ByteArrayOutputStream baos = null;
        List<StuInfo> stuInfoList = stuInfoRepository.findAll();
        HSSFWorkbook workbook = new HSSFWorkbook();   //创建Excel文档
        HSSFSheet sheet = workbook.createSheet("中员工学院学生信息表");   //创建Excel表单
        //设置表头
        HSSFRow headerRow = sheet.createRow(0);
        HSSFCell cell0 = headerRow.createCell(0);
        cell0.setCellValue("学号");
        HSSFCell cell1 = headerRow.createCell(1);
        cell1.setCellValue("姓名");
        HSSFCell cell2 = headerRow.createCell(2);
        cell2.setCellValue("学院");
        HSSFCell cell3 = headerRow.createCell(3);
        cell3.setCellValue("专业");
        HSSFCell cell4 = headerRow.createCell(4);
        cell4.setCellValue("年级");
        HSSFCell cell5 = headerRow.createCell(5);
        cell5.setCellValue("手机号");
        HSSFCell cell6 = headerRow.createCell(6);
        cell6.setCellValue("wx_id");
        HSSFCell cell7 = headerRow.createCell(7);
        cell7.setCellValue("px");
        //装数据
        for (int i = 0; i < stuInfoList.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            StuInfo stu = stuInfoList.get(i);
            row.createCell(0).setCellValue(stu.getId());
            row.createCell(1).setCellValue(stu.getSname());
            row.createCell(2).setCellValue(stu.getCollege_name());
            row.createCell(3).setCellValue(stu.getMajor_name());
            row.createCell(4).setCellValue(stu.getGrade_name());
            row.createCell(5).setCellValue(stu.getIphone());
            row.createCell(6).setCellValue(stu.getWx_id());
            row.createCell(7).setCellValue(stu.getPx());
            //  HSSFCell beginContractCell=row.createCell(8);
        }
        headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",
                new String("学生信息表.xls".getBytes("UTF-8"),"iso-8859-1"));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        baos = new ByteArrayOutputStream();
        try {
            workbook.write(baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<byte[]>(baos.toByteArray(), headers, HttpStatus.CREATED);
    }
    @PostMapping("import")
    public int importStu(MultipartFile file) {
    //    List<Student> emps=new ArrayList<>();
        int success=0;
        try {
            HSSFWorkbook workbook=new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
            int numberOfSheets=workbook.getNumberOfSheets();
            for(int i=0;i<numberOfSheets;i++) {
                HSSFSheet sheet=workbook.getSheetAt(i);
                int physicalNumberOfRows=sheet.getPhysicalNumberOfRows();
                Student student=new Student();
                for(int j=0;j<physicalNumberOfRows;j++){
                    if(j==0){
                        continue;
                    }
                    HSSFRow row=sheet.getRow(j);
                    if(row==null){
                        continue;
                    }
                    int physicalNumberOfCells=row.getPhysicalNumberOfCells();
                    student=new Student();
                    for(int k=0;k<physicalNumberOfCells;k++){
                        HSSFCell cell=row.getCell(k);
//                        switch (cell.getCellType()){}
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String cellValue=cell.getStringCellValue();
                        switch (k){
                            case 0: student.setId(cellValue);
                            break;
                            case 1:student.setName(cellValue);
                            break;
                            case 2:student.setCollegeId(cellValue);
                            break;
                            case 3:student.setMajorId(cellValue);
                            break;
                            case 4:student.setGradeId(cellValue);
                            break;
                            case 5:student.setIphone(cellValue);
                            break;
                            case 6:student.setPx(Integer.parseInt(cellValue));
                            break;
                        }
                    }
                    Student stuTemp=studentRepository.save(student);
                    if(stuTemp != null){
                        success += 1;
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success;
}



}